package com.framework;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

class Scheduler {
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
    private final Map<String, ScheduledFuture<?>> tasks = new HashMap<>();

    public void schedule(String id, Component<?, ?> component, long initialDelay, long period, TimeUnit unit) {
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(
                () -> component.execute(new ComponentContext<>()),
                initialDelay, period, unit
        );
        tasks.put(id, future);
    }

    public void cancel(String id) {
        ScheduledFuture<?> future = tasks.get(id);
        if (future != null) {
            future.cancel(false);
        }
    }
}